
package com.leaves.sys.modular.file.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.log.Log;
import com.leaves.core.context.requestno.RequestNoContext;
import com.leaves.core.exception.ServiceException;
import com.leaves.sys.modular.file.enums.SysFileInfoExceptionEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 文件下载工具类
 *
 * @author xuyuxiang
 * @date 2020/8/5 21:45
 */
public class DownloadUtil {

    private static final Log log = Log.get();

    public static void download(String fileName, byte[] fileBytes, HttpServletResponse response) {
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLUtil.encode(fileName) + "\"");
            response.addHeader("Content-Length", "" + fileBytes.length);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream;charset=UTF-8");
            IoUtil.write(response.getOutputStream(), true, fileBytes);
        } catch (IOException e) {
            log.error(">>> 下载文件异常，请求号为：{}，具体信息为：{}", RequestNoContext.get(), e.getMessage());
            throw new ServiceException(SysFileInfoExceptionEnum.DOWNLOAD_FILE_ERROR);
        }
    }
    public static void downloadMedia(String fileName, File file ,String fileSuffix, HttpServletResponse response, HttpServletRequest request) {

        response.reset();
        //获取从那个字节开始读取文件
        String rangeString = request.getHeader("Range");
        try {
            //获取响应的输出流
            OutputStream outputStream = response.getOutputStream();


            RandomAccessFile targetFile = new RandomAccessFile(file, "r");
            long fileLength = targetFile.length();
            //播放
            if(rangeString != null){

                long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                //设置内容类型
                String mimeType=getMimeType(fileSuffix);
                response.setHeader("Content-Type", mimeType);
                //设置此次相应返回的数据长度
                response.setHeader("Content-Length", String.valueOf(fileLength - range));
                //设置此次相应返回的数据范围
                response.setHeader("Content-Range", "bytes "+range+"-"+(fileLength-1)+"/"+fileLength);
                //返回码需要为206，而不是200
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                //设定文件读取开始位置（以字节为单位）
                targetFile.seek(range);
            }else {//下载

                //设置响应头，把文件名字设置好
                response.setHeader("Content-Disposition", "attachment; filename="+fileName);
                //设置文件长度
                response.setHeader("Content-Length", String.valueOf(fileLength));
                //解决编码问题
                response.setHeader("Content-Type","application/octet-stream");
            }
            byte[] cache = new byte[1024 * 300];
            int flag;
            while ((flag = targetFile.read(cache))!=-1){
                outputStream.write(cache, 0, flag);
            }
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {

        }

    }
    private static String getMimeType(String fileSuffix) {
        String mimeType =  "video/mp4";
        switch (fileSuffix){
            case "mp4":
                mimeType =  "video/mp4";
                break;
            case "webm":
                mimeType =  "video/webm";
                break;
            default:
                mimeType =  "application/octet-stream";
                break;
        }
        return mimeType;

    }
    /**
     * 下载文件
     *
     * @param file     要下载的文件
     * @param response 响应
     * @author xuyuxiang
     * @date 2020/8/5 21:46
     */
    public static void download(File file, HttpServletResponse response) {
        // 获取文件字节
        byte[] fileBytes = FileUtil.readBytes(file);
        //获取文件名称
        String fileName;
        try {
            fileName = URLEncoder.encode(file.getName(), CharsetUtil.UTF_8);
        } catch (UnsupportedEncodingException e) {
            log.error(">>> 下载文件异常，请求号为：{}，具体信息为：{}", RequestNoContext.get(), e.getMessage());
            throw new ServiceException(SysFileInfoExceptionEnum.DOWNLOAD_FILE_ERROR);
        }
        //下载文件
        download(fileName, fileBytes, response);
    }

    /**
     * 将url的文件下载到目标文件
     *
     * @param url 下载url
     * @param file 目标文件
     * @author xuyuxiang
     * @date 2021/3/25 16:51
     */
    public static void downloadToFile(String url, File file) {
        if (url == null || url.isEmpty()) throw new ServiceException(SysFileInfoExceptionEnum.DOWNLOAD_FILE_ERROR);

        if (file == null) throw new ServiceException(SysFileInfoExceptionEnum.NOT_EXISTED_FILE);

        try {
            URL uri = new URL(url);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) uri.openConnection();
            InputStream stream = connection.getInputStream();

            if (stream == null) {
                throw new ServiceException(SysFileInfoExceptionEnum.FILE_STREAM_ERROR);
            }
            FileUtil.writeFromStream(stream, file);
            connection.disconnect();
        } catch (Exception e) {
            log.error(">>> 下载文件异常，请求号为：{}，具体信息为：{}", RequestNoContext.get(), e.getMessage());
            throw new ServiceException(SysFileInfoExceptionEnum.DOWNLOAD_FILE_ERROR);
        }
    }
}
